// client.js
import * as cp from 'child_process';
import * as rpc from 'vscode-jsonrpc/lib/node/main.js';
import { fileURLToPath } from 'url';
import { dirname, join } from 'path';

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const serverPath = join(__dirname, 'server.js');

console.log('启动客户端...');

let childProcess = cp.spawn('node', [serverPath], {
    stdio: ['pipe', 'pipe', 'pipe']
});

childProcess.on('error', (error) => {
    console.error('子进程错误:', error);
});

childProcess.stderr.on('data', (data) => {
    console.error('server.js error:', data.toString());
});

childProcess.stdout.on('data', (data) => {
    console.log('server.js console:', data.toString());
});

let connection = rpc.createMessageConnection(
	new rpc.StreamMessageReader(childProcess.stdout),
	new rpc.StreamMessageWriter(childProcess.stdin));

let notification = new rpc.NotificationType('testNotification');

connection.onError((error) => {
    console.error('连接错误:', error);
});

connection.onClose(() => {
    console.log('连接已关闭');
    childProcess.kill();
});

connection.listen();

console.log('发送通知...');

for (let i = 0; i < 10; i++) {
    connection.sendNotification(notification, 'Hello World');
}

setTimeout(() => {
    console.log('关闭连接...');
    connection.dispose();
    childProcess.kill();
    process.exit(0);
}, 1000);